import 'dart:async';

import 'package:flutter/material.dart';

/* 
AnimatedList 和 ListView 类似，
 AnimatedList 可以在列表中插入或删除节点时执行一个动画
*/

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const AnimatedListPage(),
    );
  }
}

class AnimatedListPage extends StatefulWidget {
  const AnimatedListPage({super.key});

  @override
  State<AnimatedListPage> createState() => _AnimatedListPageState();
}

class _AnimatedListPageState extends State<AnimatedListPage> {
  // 指定key
  final globalKey = GlobalKey<AnimatedListState>();
  // 数据渲染
  List<String> list = ['第一条数据', '第二条数据'];
  // 一个标记  防止删除时 点击过快
  bool flag = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          list.add('this is data');
          globalKey.currentState!.insertItem(list.length - 1);
        },
        child: Icon(Icons.add),
      ),
      appBar: AppBar(title: Text('this is Appbar')),
      body: AnimatedList(
          key: globalKey,
          initialItemCount: list.length,
          itemBuilder: (context, index, animation) {
            return FadeTransition(
              opacity: animation,
              child: _buildItem(context, index),
            );
          }),
    );
  }

  _buildItem(context, index) {
    return ListTile(
      title: Text(list[index]),
      trailing: IconButton(
        icon: Icon(Icons.delete),
        onPressed: () => _deleteItem(context, index),
      ),
    );
  }

  _deleteItem(context, index) {
    if (flag) {
      flag = false;
      // 删除的核心逻辑
      setState(() {
        globalKey.currentState!.removeItem(index, (context, animation) {
          // 先获取build 再去删除
          var item = _buildItem(context, index);
          list.removeAt(index);
          return FadeTransition(
            opacity: animation,
            child: item,
          );
        });
      });
      // 开启定时器 500ms执行一次删除
      Timer.periodic(const Duration(milliseconds: 500), (timer) {
        flag = true;
        timer.cancel();
      });
    }
  }
}
